import { Breadcrumb, Button, Table, Space, Modal, Switch, Flex, TableProps, message } from 'antd';
import React, { FC } from 'react';
import { FormPanel, type FormPanelObject, FormPanelStatus, InputType, Utils } from 'lfun-bg-comp';
import _ from 'lodash';
import { format } from 'scripts/snippets/src/util/lang';
import { PageContainer } from '@/component/page-container';
import utils from '@/utils';
import { SearchStudentSessionInfo, create, search, update } from '@/service/student/session';
import { SESSION_STATUS } from '@/constant/studentOptions';
import PermissionButton, { isPermission, isPermissionOperate } from '@/component/permission-button';

const Create: React.FC<{ show: boolean; onChange: Function; onSave: Function }> = ({ show, onChange, onSave }) => {
  const list = [
    {
      title: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 24,
      inputs: [
        {
          label: '届别',
          name: 'session_name',
          key: 'session_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '届别名称',
          name: 'session_alias',
          key: 'session_alias',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '年度',
          name: 'year',
          key: 'year',
          required: true,
          inputProps: {
            picker: 'year',
          },
          inputType: InputType.date,
          formatSubmitValue: value => {
            if (value && value.isValid && value.isValid()) return value.format('YYYY');
            return value;
          },
        },
      ],
    },
  ];

  return (
    <>
      <Modal title="新届别设置" width="40%" footer={[]} open={show} onCancel={() => onChange(false)}>
        <FormPanel
          btnsAlign="center"
          restBtnText="返回"
          submitBtnText="确定"
          buttonsDisplay="block"
          onReset={() => onChange(false)}
          onFinish={onSave}
          template={list}
        />
      </Modal>
    </>
  );
};

const Groups: FC = () => {
  //const [searchForm, setSearchForm] = React.useState<any>();
  const [formObjectPanel, setFormObjectPanel] = React.useState<any>();
  const [value, setValue] = React.useState([]);
  const [filterVal, setFilterVal] = React.useState(null);

  const [showModel, setShowModel] = React.useState(false);
  const [cur, setCur] = React.useState<any>();
  const [loading, setLoading] = React.useState(false);

  const searchFunc = async () => {
    setLoading(true);
    utils.showLoading();
    const parmas: SearchStudentSessionInfo = {
      //...searchForm?.getFieldsValue(),
    };
    const res = await search(parmas, 1, 1000);
    if (res.success) {
      setValue(res.data.items);
    } else {
      formObjectPanel.reVaildation(res);
    }
    utils.hideLoaing(res.success);
    setLoading(false);
    return res;
  };

  React.useEffect(() => {
    searchFunc();
  }, []);

  function handleView(record) {
    setCur(record);
    setShowModel(true);
  }

  const columns: TableProps['columns'] = [
    {
      title: '编码',
      dataIndex: 'session_id',
      key: 'session_id',
    },
    {
      title: '届别名称',
      dataIndex: 'session_name',
      key: 'session_name',
    },
    {
      title: '届别别名',
      dataIndex: 'session_alias',
      key: 'session_alias',
    },
    {
      title: '年度',
      dataIndex: 'year',
      key: 'year',
    },
    {
      title: '状态',
      dataIndex: 'session_status',
      key: 'session_status',
      fixed: 'right',
      width: 100,
      render: (text, record) => {
        return (
          <Switch
            checked={text === 'enable'}
            disabled={!Utils.getProps('isSchool') || !isPermission({ permission: 'status' })}
            onClick={async () => {
              const isEnable = text === 'disable';
              const _value = value;
              try {
                if (isEnable) {
                  const enableList = _.filter(_value, { session_status: 'enable' });
                  if (enableList.length > 0) {
                    const res1 = update({ ...enableList[0], session_status: 'disable' });
                    if (res1.success) {
                      throw new Error();
                    }
                  }
                }
                const res = await update({ ...record, session_status: isEnable ? 'enable' : 'disable' });
                if (res.success) {
                  _value.forEach(v => {
                    if (v.session_id === record.session_id) {
                      v.session_status = 'enable';
                    } else if (v.session_status === 'enable') {
                      v.session_status = 'disable';
                    }
                  });
                  (filterVal || []).forEach(v => {
                    if (v.session_id === record.session_id) {
                      v.session_status = 'enable';
                    } else if (v.session_status === 'enable') {
                      v.session_status = 'disable';
                    }
                  });
                  if (filterVal) setFilterVal([...filterVal]);
                  setValue([..._value]);
                }
              } catch {
                message.error('届别开启失败');
              }
            }}
          />
        );
      },
    },
    {
      title: '操作',
      key: 'actions',
      fixed: 'right',
      //width: 100,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '届别名称',
          name: 'session_name',
          key: 'session_name',
          textRange: [0, 20],
        },
        {
          label: '届别别名',
          name: 'session_alias',
          key: 'session_alias',
          textRange: [0, 20],
        },
        {
          label: '状态',
          name: 'session_status',
          key: 'session_status',
          inputType: InputType.select,
          renderOption: SESSION_STATUS,
        },
      ],
    },
  ];
  const showList = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      span: 12,
      inputs: [
        {
          label: '届别名称',
          name: 'session_name',
          key: 'session_name',
        },
        {
          label: '届别别名',
          name: 'session_alias',
          key: 'session_alias',
        },
        {
          label: '状态',
          name: 'session_status',
          key: 'session_status',
          inputType: InputType.select,
          renderOption: SESSION_STATUS,
        },
      ],
    },
  ];

  const [showCreateModel, setShowCreateModel] = React.useState(false);
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '届别管理' }]} />}>
      <FormPanel
        btnsAlign="right"
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(formObjectPanel: FormPanelObject) => {
          //setSearchForm(form);
          setFormObjectPanel(formObjectPanel);
        }}
        onFinish={async (formObjectPane: FormPanelObject) => {
          const values = formObjectPane.getFieldsValue();
          let filterVal = values;
          if (!(filterVal && filterVal.length > 0)) {
            filterVal = await searchFunc();
          }
          filterVal = filterVal.filter(v => {
            return (
              v.session_name.indexOf(values.session_name || v.session_name) !== -1 &&
              v.session_alias.indexOf(values.session_alias || v.session_alias) !== -1 &&
              v.session_status.indexOf(values.session_status || v.session_status) !== -1
            );
          });
          setFilterVal(filterVal);
        }}
        template={list}
      />
      <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
        {Utils.getProps('isSchool') && (
          <PermissionButton permission="add">
            <Button type="primary" onClick={() => setShowCreateModel(true)}>
              添加届别
            </Button>
          </PermissionButton>
        )}
      </Flex>
      <Table
        loading={loading}
        dataSource={filterVal || value}
        columns={columns}
        pagination={false}
        scroll={{ x: 'max-content' }}
      />
      <Modal title="查看届别" width="800px" open={showModel} footer={null} onCancel={() => setShowModel(false)}>
        <FormPanel
          btnsAlign="center"
          restBtnText="返回"
          submitBtnText="确定"
          values={cur}
          formStatus={FormPanelStatus.nonEdit}
          buttonsDisplay="none"
          onReset={() => setShowModel(false)}
          onFinish={() => {}}
          template={showList}
        />
      </Modal>
      <Create
        show={showCreateModel}
        onChange={setShowCreateModel}
        onSave={async (formObjectPanel: FormPanelObject) => {
          const values = formObjectPanel.getFieldsValue();
          values.session_status = 'disable';
          const res = await create(values);
          if (res.success) {
            setShowCreateModel(false);
            formObjectPanel.resetFields();
            message.success('添加成功');
            //setFilterVal([values].concat(filterVal || value));
            searchFunc();
            setFilterVal(null);
          } else {
            formObjectPanel.reVaildation(res);
          }
        }}
      />
    </PageContainer>
  );
};

export default Groups;
